-module(server).

-behaviour(gen_server).

-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

start_link() ->
    gen_server:start_link(?MODULE, [8989], []).

init([Port]) -> 
    {ok, LSock} = gen_tcp:listen(Port, [binary, {reuseaddr, true}, {active, true}]),
    {ok, LSock, 0}.

handle_call(_Msg, _From, State) ->
    {reply, ok, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.
    
handle_info({tcp, Socket, Data}, State) ->
    io:format("receive data from ~p : ~p~n", [Socket, Data]),
    {noreply, State};
handle_info({tcp_closed, _Socket}, State) ->
    io:format("socket close~n"),
    {stop, normal, State};
handle_info(timeout, LSock) ->
    {ok, ClientSocket} = gen_tcp:accept(LSock),
    io:format("receive connection ~p~n", [ClientSocket]),
    {noreply, ClientSocket};
handle_info(Msg, State) ->
    io:format("Unexpected message: ~p~n", [Msg]),
    {noreply, State}.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}. 
    
terminate(Reason, _State) ->
    io:format("tcp terminate due to ~p~n", [Reason]),
    ok.     
